package com.sanjiahantang.youjiaclient.module.goods.views.impl;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.RefreshRecyclerView;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseApplication;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.module.common.beans.ConditionBean;
import com.sanjiahantang.youjiaclient.module.common.views.impl.SearchActivity;
import com.sanjiahantang.youjiaclient.module.goods.presenters.GoodsPresenter;
import com.sanjiahantang.youjiaclient.module.goods.views.GoodsView;
import com.sanjiahantang.youjiaclient.utils.KeyBoardUtils;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;

/**
 * 商品列表页面
 */
public class GoodsListActivity extends BaseMvpActivity<GoodsView, GoodsPresenter> implements
        GoodsView, View.OnClickListener,
        RefreshRecyclerView.OnLoadMoreListener {

    private RefreshRecyclerView goodsList;
    private GridLayoutManager gridLayoutManager;
    private SwipeRefreshLayout refresh;


    private View ffStyle, ffRoomType, ffPrice, llMask, priceView, btnPriceSubmit,btnPriceClear;
    private TextView txtStyle, txtRoomType, txtPrice, txtTitle;
    private ImageView ivStyle, ivRoomType, ivPrice;
    private ListView optionList;
    private MagicIndicator miTabs;
    private int colorPrimary, text_gary_color;
    private String keywords;
    private EditText etPriceSt, etPriceEd;
    private int categoryId;
    private String orderCode;
    private String typeGoodsId = null;
    private String findsimilar;


    @Override
    public GoodsPresenter initPresenter() {
        return new GoodsPresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_goods_list);
        categoryId = getIntent().getIntExtra("id", 0);
        orderCode = getIntent().getStringExtra("orderCode");
        keywords = getIntent().getStringExtra(KEY_KEYWORDS);
        miTabs = (MagicIndicator) findViewById(R.id.miTabs);

        presenter.setOnLoadListener(new BaseView.OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                Object[] param = (Object[]) content;
                switch ((int) param[0]) {
                    case CALLBACK_TYPE_RECYCLER_ADAPTER:
                        goodsList.setAdapter((RecyclerView.Adapter) param[1]);
                        goodsList.switchLayoutManager(gridLayoutManager);

                        break;
                    case CALLBACK_TYPE_QUICK_ADAPTER:
                        optionList.setAdapter((ListAdapter) param[1]);
                        break;
                    case CALLBACK_TYPE_RECOVER:
                        recoverDefault();
                        if (param[1] != null && param[1] instanceof ConditionBean.SelectorData){
                            ConditionBean.SelectorData resultData = (ConditionBean.SelectorData) param[1];
                            if (resultData.getParentId() == null){
                                //band
                                if (resultData.getDicValue() == null){
                                    txtRoomType.setText("品牌");
                                }else{
                                    txtRoomType.setText(resultData.getDicName());
                                }
                            }else{
                                if (resultData.getDicValue() == null){
                                    txtStyle.setText("风格");
                                }else{
                                    txtStyle.setText(resultData.getDicName());
                                }
                            }
                        }
                        break;
                    case CALLBACK_TYPE_LIST:
                        final CommonNavigator commonNavigator = new CommonNavigator($this);
                        commonNavigator.setAdapter((CommonNavigatorAdapter) param[1]);
                        miTabs.setNavigator(commonNavigator);
                        break;
                }
            }
        });
        typeGoodsId = getIntent().getStringExtra(KEY_TYPE_GOODSID);
        findsimilar = getIntent().getStringExtra("FIND");
        if (typeGoodsId != null || findsimilar != null) {
            findViewById(R.id.selectorBar).setVisibility(View.GONE);
        }
        goodsList = (RefreshRecyclerView) findViewById(R.id.goods_list);
        refresh = (SwipeRefreshLayout) findViewById(R.id.goods_list_refresh);
        findViewById(R.id.back).setOnClickListener(this);
        goodsList.setLoadMoreEnable(true);
        goodsList.setOnLoadMoreListener(this);
        gridLayoutManager = new GridLayoutManager(this, 2);
        goodsList.setLayoutManager(gridLayoutManager);


        goodsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                refresh.setEnabled(topRowVerticalPosition >= 0);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                presenter.resetGoodsList($this);
            }
        });


        colorPrimary = $this.getResources().getColor(R.color.colorPrimary);
        text_gary_color = $this.getResources().getColor(R.color.gray);
        optionList = (ListView) $this.findViewById(R.id.optionList);
        ffStyle = $this.findViewById(R.id.ffStyle);
        ffRoomType = $this.findViewById(R.id.ffRoomType);
        ffPrice = $this.findViewById(R.id.ffPrice);
        llMask = $this.findViewById(R.id.llMask);
        txtStyle = (TextView) $this.findViewById(R.id.txtStyle);
        txtRoomType = (TextView) $this.findViewById(R.id.txtRoomType);
        txtPrice = (TextView) $this.findViewById(R.id.txtPrice);
        ivStyle = (ImageView) $this.findViewById(R.id.ivStyle);
        ivRoomType = (ImageView) $this.findViewById(R.id.ivRoomType);
        ivPrice = (ImageView) $this.findViewById(R.id.ivPrice);
        priceView = findViewById(R.id.priceView);
        btnPriceSubmit = findViewById(R.id.btnPriceSubmit);
        btnPriceClear = findViewById(R.id.btnPriceClear);
        etPriceSt = (EditText) findViewById(R.id.etPriceSt);
        etPriceEd = (EditText) findViewById(R.id.etPriceEd);

        btnPriceClear.setOnClickListener(this);
        ffStyle.setOnClickListener(this);
        ffRoomType.setOnClickListener(this);
        ffPrice.setOnClickListener(this);
        llMask.setOnClickListener(this);
        btnPriceSubmit.setOnClickListener(this);
        findViewById(R.id.llSearchBar).setOnClickListener(this);

        txtTitle = (TextView) findViewById(R.id.txtTitle);
        String title = "输入关键字";
        if (!TextUtils.isEmpty(keywords)) {
            title = keywords;
        } else if (getIntent().hasExtra(KEY_TITLE)) {
            title = getIntent().getStringExtra(KEY_TITLE);
        }

        txtTitle.setText(title);

    }

    @Override
    public void initData() {
        presenter.loadSelectors($this, categoryId, keywords, orderCode, typeGoodsId, findsimilar);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.ffStyle:
                onSelectorClicked(txtStyle, ivStyle, TYPE_STYLE);
                break;
            case R.id.ffRoomType:
                onSelectorClicked(txtRoomType, ivRoomType, TYPE_ROOM_TYPE);
                break;
            case R.id.ffPrice:
                if (priceView.getVisibility() == View.GONE) {
                    recoverDefault();
                    txtPrice.setTextColor(colorPrimary);
                    ivPrice.setImageResource(R.drawable.i_up_green);
                    llMask.setVisibility(View.VISIBLE);
                    priceView.setVisibility(View.VISIBLE);
                } else {
                    recoverDefault();
                }
                break;
            case R.id.llMask:
                recoverDefault();
                break;
            case R.id.btnPriceSubmit:
                checkPrice();
                break;
            case R.id.llSearchBar:
                Intent intent = new Intent($this, SearchActivity.class);
                intent.putExtra(KEY_TYPE, SEARCH_TYPE_GOODS_FROM_LIST);
                startActivityForResult(intent,INTENT_SEARCH);
                BaseApplication.addActivity(this);
                break;
            case R.id.btnPriceClear:
                clearPrice();
                break;
        }
    }

    private void clearPrice() {
        presenter.resetGoodsList($this, -1, DEFAULT_PAGE_SIZE);
        recoverDefault();
        etPriceSt.setText("");
        etPriceEd.setText("");
        txtPrice.setText("价格区间");
    }

    private void checkPrice() {
        if (TextUtils.isEmpty(etPriceSt.getText()) || TextUtils.isEmpty(etPriceEd.getText())) {
            return;
        }
        try{
            int priceSt = Integer.valueOf(etPriceSt.getText().toString());
            int priceEd = Integer.valueOf(etPriceEd.getText().toString());
            if (priceEd > priceSt) {
                presenter.resetGoodsList($this, priceSt, priceEd);
                recoverDefault();
                txtPrice.setText(priceSt + " 元 - " + priceEd + " 元");
            } else {
                Utils.showToast($this, "价格输入有误");
            }
        }catch (Exception e){
            Utils.showToast($this, "价格输入有误");
        }


    }

    private void onSelectorClicked(TextView tv, ImageView iv, int type) {
        if (llMask.getVisibility() == View.GONE) {
            presenter.resetAdapterData(type);
            tv.setTextColor(colorPrimary);
            iv.setImageResource(R.drawable.i_up_green);
            llMask.setVisibility(View.VISIBLE);
            optionList.setVisibility(View.VISIBLE);
        } else {
            recoverDefault();
        }
    }

    public void recoverDefault() {
        txtStyle.setTextColor(text_gary_color);
        txtRoomType.setTextColor(text_gary_color);
        txtPrice.setTextColor(text_gary_color);

        ivStyle.setImageResource(R.drawable.i_down_gray);
        ivRoomType.setImageResource(R.drawable.i_down_gray);
        ivPrice.setImageResource(R.drawable.i_down_gray);

        llMask.setVisibility(View.GONE);
        optionList.setVisibility(View.GONE);
        priceView.setVisibility(View.GONE);

        KeyBoardUtils.closeKeybord(etPriceSt, $this);
        KeyBoardUtils.closeKeybord(etPriceEd, $this);
    }


    @Override
    public void showProgress() {
        super.showProgress($this);
    }


    @Override
    public void loadMoreListener() {
        presenter.getMoreList($this);
    }


    @Override
    public void hideProgress() {
        super.hideProgress();
        refresh.setRefreshing(false);
        goodsList.notifyData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INTENT_SEARCH && resultCode == RESULT_OK){

            keywords = data.getStringExtra(KEY_KEYWORDS);
            if (TextUtils.isEmpty(keywords)){
                txtTitle.setText("输入关键字");
            }else{
                txtTitle.setText(keywords);
            }

            presenter.loadSelectors($this, 0, keywords, null, typeGoodsId, findsimilar);

            txtStyle.setText("品牌");
            txtRoomType.setText("风格");
            txtPrice.setText("价格区间");
            etPriceSt.setText("");
            etPriceEd.setText("");
        }
    }
}
